<template>
  <div style="height: 100%">
    <el-form v-if="origin == ''" :inline="true" label-width="120px"  style="padding-left: 16px" class="bi-toolbar">
      <el-button size="mini" class="bi-el-btn "  icon="el-icon-arrow-left" @click="backClick" >返回</el-button>
      <el-button size="mini" class="bi-el-btn "   @click="dataSaveAndSubmit(true)" :disabled="twoButtonsController === 0 || twoButtonsController === 2">保存并提交</el-button>
      <el-button size="mini" class="bi-el-btn "   @click="fetchBack()" :disabled="twoButtonsController !==2" v-if="twoButtonsController === 2">取回</el-button>
      <el-button  size="mini" class="bi-el-btn "  @click="dataSaveAndSubmit(false)" :disabled="saveButtonController !== 1">保存</el-button>
    </el-form>

    <!--页面主体内容——新建申请的内容-->
    <el-form :model="requestItem" :rules="rules"  ref="ruleForm" label-width="100px" class="demo-ruleForm" style="height: calc(100% - 50px);overflow: auto;" :disabled="disabled">
      <el-form-item label="申请资源"  style="margin-bottom: 0px;" class="elFormItemFirst" required>
        <!--勾选资源提示-->
        <div class="topInformationDisplay" v-if="origin !== '0'" >
          (提示:一个申请内信息资源所属部门必须相同)
        </div>
      </el-form-item>

        <!--当“个人工作台”中“我的待办”获取此页面时，不再以“左选右组件”展示已选资源，以“我的申请主页面中用到的数量统计页面”展示已选资源-->
        <selected-data-statistical-details
            v-if="origin === '0'"
            style="height: 256px;width: 880px;padding-top: 10px;overflow-y: auto"
            :ida-guid="requestItem.idaGuid"
            :ires-guids="requestItem.resGuid">
        </selected-data-statistical-details>
        <double_tree_transfer
            v-else
            class="firstCard"
            :selectedResArr.sync="selectedResArr"
            :currDeptCode.sync ="currDeptCode"
            :operateControl.sync = "disabled"
            :origin.sync = "origin"
            :isApply = "isApply"
            @getSelectedNumber="getSelectedNumber"
        >
        </double_tree_transfer>

      <el-form-item label="申请有效期" prop="combineValidateTime">
        <div class="block">
          <el-date-picker
              align="center"
              v-model="requestItem.combineValidateTime"
              value-format='yyyy-MM-dd HH:mm:ss'
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00','23:59:59']"
              :picker-options="pickerOptions0"
          >
          </el-date-picker>
        </div>
      </el-form-item>

      <el-form-item label="申请人" prop="reqUserName">
        <el-input v-model="requestItem.reqUserName" disabled style="width: 750px;"></el-input>
      </el-form-item>

      <el-form-item
          label="申请理由"
          class="applyReason"
          prop="reqReason">
        <el-input type="textarea" v-model="requestItem.reqReason" style="width: 750px" :rows="4"></el-input>
      </el-form-item>
    </el-form>


    <!--多态询问框-->
    <agilePolymorphicConfirm
        :show.sync="isShowmcDialog"
        content="存在新建申请内容，是否保存？"
        title="提示"
        @confirm="mcConfirm"
        @abandon="mcAbandon"
        @cancel="mcCancel"
    ></agilePolymorphicConfirm>
  </div>
</template>

<script>
import { inforesApi } from "@/api/irpApi";
import DoubleTreeTransfer from "@/views/dataqueryrequest/DoubleTreeTransfer";
import selectedDataStatisticalDetails from "@/views/dataqueryrequest/SelectedDataStatisticalDetails";
const ORIGINS ={
    //个人工作台-查看
    "0":true,
    //我的申请-查看
    "1":true,
    // 编辑
    "2":false,
    // 从资源浏览申请进入的编辑
    "3":false
}
export default {
  name: "CreateDataQueryRequest",
  mounted() {
    this.saveButtonController = -1
    inforesApi.getUserInformation().then((result) =>{
      this.requestItem.reqUserName = result.userName
    })

    if(this.idaGuid !='' ){
        let data = {
          idaGuid : this.idaGuid
        }
        // 根据idaGuid获取申请记录
        inforesApi.getOneApplicationInforResource(data).then(res => {
            this.requestItem.idaGuid = this.idaGuid
            this.requestItem.resGuid = res.itemVo.resGuid
            this.requestItem.fieldList = res.itemVo.fieldList
            this.requestItem.reqUserName =  res.itemVo.reqUserName
            this.requestItem.reqReason = res.itemVo.reqReason

            this.requestItem.validStartTime = res.itemVo.validStartTime
            this.requestItem.validEndTime = res.itemVo.validEndTime
            this.selectedResArr = res.selectedResArr
            this.currDeptCode = res.currDeptCode
            if(this.requestItem.validStartTime != ''){
              this.requestItem.combineValidateTime = [new Date(this.requestItem.validStartTime),new Date(this.requestItem.validEndTime)]
            }
          this.getTimeFn();
          this.$nextTick(() => {
              this.saveButtonController = 0
              //设置默认时间
            })
        })
    }else{
      this.getTimeFn();
      this.$nextTick(() => {
          this.saveButtonController = 0
          //设置默认时间
        })
    }
  },
  props:{
    idaGuid:{
      type:String ,
      required:false,
      default:""
    },
    resGuid:{
      type:String ,
      required:false,
      default:""
    },
    origin:{
        type:String,
        required:false,
        default:""
    },
    isDirty:{
        type:Boolean,
        required:false,
        default:false
    },
    isAttachAction:{
      type:Boolean,
      required:false,
      default:false,
    }
  },
  components:{
    'double_tree_transfer':DoubleTreeTransfer,
    'selected-data-statistical-details':selectedDataStatisticalDetails
  },
  data(){
    let reasonCheck = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请填写申请理由'));
      }else if (/[/\\*<>"'\\|?:]/.test(value)) {
        callback(new Error('标题不能包含\\ 、/ 、: 、* 、? 、" 、\' 、< 、> 、|中任意字符'));
      }else if (value.length > 200) {
        callback(new Error('申请理由不能超过200个字符'))
      }else {
        callback();
      }
    };
    return {
//表单开始
      rules: {
        combineValidateTime: [
          { type: 'array', required: true, message: '请选择日期', trigger: 'change' }
        ],
        reqReason:[
          { validator: reasonCheck, trigger: 'blur' }
          // {  required: true, message: '请填写申请理由', trigger: 'blur' }
        ]
      },
      //控制时间选择器  只能选取今天及之后的时间
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
//表单结束


      // 控制“保存”按钮的显示
      saveButtonController:-1,
      // 控制“保存并提交”、“取回”按钮的显示
      twoButtonsController:0,
      // 单独保存操作是否成功
      onlySubmit:false,

      //后端需获取的数据
      requestItem:{
        reqReason:'',
        reqUserName:'',
        validStartTime:'',
        validEndTime:'',
        resArr:[],
        combineValidateTime:['','']
      },
      // 当前保存的申请项guid
      idaGuids:[],
      // 多态询问框控制
      isShowmcDialog:false,
      selectedResArr:[],
      currDeptCode:"",
      currIdaGuid:this.idaGuid,
      currWfInstanceGuid:'',
    //   是否已提交，提交后设置为true，影响页面是否可再次编辑
      submited:false,
      otherIsAttachAction:this.isAttachAction,
      isApply:true
    }
  },
  computed: {
    disabled:function(){
        return ORIGINS[this.origin] || this.submited
    }
  },
  watch:{
    'requestItem.resArr':{
      deep:true,
      handler:function () {
        if(this.saveButtonController == 0){

          this.saveButtonController = 1
          this.twoButtonsController = 1
          //做修改操作后   onlySubmit恢复初始值  false
          this.onlySubmit = false
        }
      }
    },
    'requestItem.reqReason':{
      deep:true,
      handler:function () {
        if(this.saveButtonController == 0){
          this.saveButtonController = 1
          this.twoButtonsController = 1
          //做修改操作后   onlySubmit恢复初始值  false
          this.onlySubmit = false
        }
      }
    },
    'requestItem.combineValidateTime':{
      deep:true,
      handler(newValue,oldValue){
        if(this.saveButtonController != -1){
            this.requestItem.validStartTime = this.requestItem.combineValidateTime[0]
            this.requestItem.validEndTime = this.requestItem.combineValidateTime[1]
        }
        if(this.saveButtonController == 0){
          this.saveButtonController = 1
          this.twoButtonsController = 1
          //做修改操作后   onlySubmit恢复初始值  false
          this.onlySubmit = false
        }
      }
    },
    saveButtonController:{
        handler(n,o){
            if(n ==1){
                this.$emit("update:isDirty",true);
            }
        }
    }
  },
  methods:{
    //返回
    'backClick':function () {
      if (this.saveButtonController === 1) {
        this.isShowmcDialog = true
      }else {
        this.$emit('update:linkageVisible', false)
      }
    },
    lengthBetterThanOne: function (that, possibleSubmit,callback) {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          //判断是否为   续期和重新提交操作
          if (that.otherIsAttachAction) {
            that.currIdaGuid = ''
            that.otherIsAttachAction = false
          }
          let data = {
            idaGuid: that.currIdaGuid,
            data: JSON.stringify(that.requestItem)
          }
          if (possibleSubmit) {
            data.possibleSubmit = true
            data.onlySubmit = that.onlySubmit
          }
          inforesApi.dataqueryCreateAndUpdate(data).then((res) => {
            if (callback) {
              callback(res)
            }
            that.requestItem.idaGuid = res.idaGuid
            that.currIdaGuid = res.idaGuid
            that.currWfInstanceGuid = res.wfInstanceGuid
           
            //存在提交操作
            if (possibleSubmit) {
              that.submited = true;
              that.onlySubmit = false;
            }
            //只保存操作
            if (!possibleSubmit) {
              that.onlySubmit = true
            }
            that.saveButtonController = 0

            //当点击“保存并提交”按钮后，该按钮失效
            if (possibleSubmit) {
              that.twoButtonsController = 2
            }
          })
        } else {
          if (callback) {
            callback(false)
          }
        }
      })
    },
    // 保存与提交
    'dataSaveAndSubmit':function (possibleSubmit,callback) {
      let that = this

      if (this.requestItem.resArr.length === 0) {
        this.$BI.Dialog.error("请选择申请资源")
      }else{
        this.lengthBetterThanOne(that, possibleSubmit,callback);
      }
    },
    // 取回
    fetchBack(){
      let that = this
      let datas={
        'idaGuid':that.currIdaGuid,
        'wfInstanceGuid':that.currWfInstanceGuid
      }
      inforesApi.dataqueryFetchBack(datas).then(res => {
        that.twoButtonsController = 1
        that.submited = false
      })
    },
    confirmHandle:function(v1,callback){
        let that = this
        if (this.requestItem.resArr.length === 0) {
            this.$BI.Dialog.error("请选择申请资源")
            if(callback instanceof Function){
                callback(false)
            }
        }else{
            if(callback instanceof Function){
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                    callback(that.requestItem)
                    }else{
                    callback(false)
                    }
                    that.saveButtonController = 0
                })
            }else{
                that.saveButtonController = 0
                return that.requestItem
            }
        }
    },
//表单开始
    //左选右开始
    getSelectedNumber(value){
      //获取选择的资源和指标
      this.requestItem.resArr = value
    },
    //左选右结束

    //获取默认时间范围
    getTimeFn() {
      if (this.requestItem.validStartTime === '') {
        let start = new Date();
        let end  = this.getDelayDate(start,1)

        let startTime = this.timeFormatConversion(start)
        let endTime = this.timeFormatConversion(end)

        this.requestItem.validStartTime = startTime+' '+'00:00:00'
        this.requestItem.validEndTime = endTime+' '+'23:59:59'


        this.requestItem.combineValidateTime =[new Date(this.requestItem.validStartTime),new Date(this.requestItem.validEndTime)]
      }
    },
    timeFormatConversion(date){
      let  dateInfo = new Date(date);
      let  y = dateInfo.getFullYear();
      let  m = dateInfo.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      let  d = dateInfo.getDate();
      d = d < 10 ? ('0' + d) : d;
      let time = y + '-' + m + '-' + d;
      return time
    },
    /*
    *  desc 返回从某年某月某日指定增加n个月的日期
    *  params  originalDate 原始年月日
    *          addMonth     增加月数
    *  return Date
    */
    getDelayDate :function (originalDate, addMonth) {
      //不改变原始日期originalDate
      let  originDate = new Date(originalDate.getFullYear(),originalDate.getMonth(),originalDate.getDate());
      originDate.setHours(originalDate.getHours());
      originDate.setMinutes(originalDate.getMinutes());
      originDate.setSeconds(originalDate.getSeconds());
      //获取当前天数
      let  oldDate = originDate.getDate();
      //获取增加后的月数
      let  newMonth = originDate.getMonth() + addMonth;
      //开始跳转到指定月份，年份会自动增加
      originDate.setMonth(newMonth);
      //0-11间循环
      let  realMonth = newMonth % 12;
      //跳转月份 不是 预期月份
      if (originDate.getMonth() !== realMonth) {
        originDate.setMonth(realMonth);
        //利用setDate(0)是返回上一个月的最大天数,获取真实月份最大天数
        originDate.setDate(new Date(originDate.getFullYear(), originDate.getMonth() + 1, 0).getDate());
      }
      //保持日期的准确性 使之不会超过某月的最大天数
      if (oldDate < originDate.getDate()) {
        originDate.setDate(oldDate);
      }
      return originDate;
    },
//表单结束

    // 多态询问框 开始
    mcConfirm:function (){
      this.dataSaveAndSubmit(false, (res) => {
        if (res) {
          this.$emit('update:linkageVisible', false)
          this.isShowmcDialog = false
        }
      })
    },
    mcAbandon(){
      this.$emit('update:linkageVisible', false)
      this.isShowmcDialog = false
    },
    mcCancel(){
      this.isShowmcDialog = false
    }
    // 多态询问框  结束
  }
}
</script>

<style scoped>
.topInformationDisplay{
  /*border: 1px red solid;*/
  width: 280px;
}
.firstCard{
  width: 1060px;
  height: 500px;
  margin-left: 8px;
  margin-bottom: 22px;
}
.block /deep/ .el-date-editor .el-range-separator {
  padding: 0 5px;
  line-height: 24px;
  width: 5%;
  color: #303133;
}
.block /deep/ .el-date-editor .el-range__icon {
  font-size: 14px;
  margin-left: -5px;
  color: #C0C4CC;
  float: left;
  line-height: 26px;
}
.block /deep/ .el-date-editor .el-range__close-icon {
  font-size: 14px;
  color: #C0C4CC;
  width: 25px;
  display: inline-block;
  float: right;
  line-height: 24px;
}
.applyReason /deep/ label:before {
  content: '* ';
  color: #f8836c;
  font-size: 100%;
}


</style>